﻿@model List<DHQGHN.PM2.Models.Online.Resident1>
@*<script src="~/Scripts/jquery-1.10.2.js"></script>*@
<style>
    input {
        text-transform: capitalize;
    }
</style>
<script>
    @functions{
         public string GetAntiForgeryToken()
         {
             string cookieToken, formToken;
             AntiForgery.GetTokens(null, out cookieToken, out formToken);
             return cookieToken + "," + formToken;
         }
     }
    function KiemTraChuHo() {

        $(".RELATION_ID_DROPDOWN").on('focus', function () {
            previous = this.value;
        }).change(function () {
            input = $(this);
            if (input.val() != '1') {
                return;
            }
            count = 0;
            $('.RELATION_ID_DROPDOWN').each(
            function (i, item) {
                if ($(item).val() == '1') {
                    count++;
                }
            }

        );
            if (count >= 2) {
                $("#dialog-confirm").dialog({
                    resizable: false,
                    width: 400,
                    height: 140,
                    modal: true,
                    buttons: {
                        "Có thay đổi": function () {
                            input.val('1');
                            $('.RELATION_ID_DROPDOWN').each(function (i, item) {
                                if ($(item).val() == '1') {
                                    $(item).val('0');
                                }
                            });
                            input.val('1');
                            $(this).dialog("close");
                        },
                        "Không thay đổi": function () {
                            input.val(previous);
                            $(this).dialog("close");

                        }
                    },
                });
            }
        });
    }
    $(document).ready(function () {

        KiemTraChuHo();
        $("#btnNext").click(function (event, giatri) {
            if (giatri != null) {
                btnClickButton(giatri);
            }
            else {
                btnClickButton("1");
            }
        });
        $("#btnBack").click(function () {
            btnClickButton("back")
        });


        $('#btnAddResident').click(function () {
            $('#divResidentList').append($('#divAddNewResident').html());
            KiemTraChuHo();
        });

    });

    function btnClickButton(isback) {
        var isValidate = true;

        $('validation-summary-errors').html('');

        $('#messageResident').text();


        var datasend = [];
        $('form').validate(true);

        if (isback == 'back') {
            $("#divLoading").show();
            $('#btnNext').attr('disabled', true);
            $('#btnBack').attr('disabled', true);

            $.ajax({
                url: '@Url.Action("Pin","Online")',
                dataType: 'html',
                method: 'get',
                cache: false,
                headers: {
                    'VerificationToken': '@GetAntiForgeryToken()'
                },
                data: {
                    'IdLoginCode': $('[name="HOUSEHOLD_ID"]').first().val(),
                    'pin': '-1'
                },
                success: function myfunctionSuccess(data, textStatus, jqXHR) {
                    $('#formLogin').html(data);
                    $('#btnSaveandLogout').css("visibility", "visible");

                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('Có lỗi xảy ra trong quá trình đăng nhập: ' + errorThrown);
                },
                complete: function (jqXHR, textStatus) {
                    $("#divLoading").hide();
                    $('#btnNext').removeAttrs('disabled');
                    $('#btnBack').removeAttrs('disabled');

                }

            });
            return;
        }

        var checkDataRessident = true;
        $('#divResidentList').find('.datarow').each(function (i, item) {
            var checkValue = true
            var lastName = $(item).find('[name="LAST_NAME"]');

            var middleName = $(item).find('[name="MIDDLE_NAME"]');

            var firstName = $(item).find('[name="FIRST_NAME"]');

            var gender = $(item).find('[name="GENDER_ID"]');

            var residentId = $(item).find('[name="RESIDENT_ID"]');

            var householdId = $(item).find('[name="HOUSEHOLD_ID"]');

            var ethnicId = $(item).find('[name="ETHNIC_ID"]');

            var relationId = $(item).find('[name="RELATION_ID"]');


            if (lastName.val().length > 0 || firstName.val().length > 0 || ethnicId.val().length > 0 || gender.val().length > 0) {
                if (lastName.val().length <= 0) {
                    checkValue = false;
                    $(item).find('[name="LAST_NAME"]').next().text("Yêu cầu nhập 'Họ' ");
                }
                if (firstName.val().length <= 0) {
                    checkValue = false;
                    $(item).find('[name="FIRST_NAME"]').next().text("Yêu cầu nhập 'Tên khai sinh' ");
                }
                if (ethnicId.val().length <= 0) {
                    checkValue = false;
                    $(item).find('[name="ETHNIC_ID"]').next().next().text("Yêu cầu nhập 'Dân tộc' ");
                }
                if (gender.val().length <= 0) {
                    checkValue = false;
                    $(item).find('[name="GENDER_ID"]').next().next().text("Yêu cầu nhập 'Giới tính' ");
                }

            } else if (middleName.val().length > 0 || relationId.val().length > 0) {
                $(item).find('[name="LAST_NAME"]').next().text("Yêu cầu nhập 'Họ' ");
                $(item).find('[name="FIRST_NAME"]').next().text("Yêu cầu nhập 'Tên khai sinh' ");
                $(item).find('[name="ETHNIC_ID"]').next().next().text("Yêu cầu nhập 'Dân tộc' ");
                $(item).find('[name="GENDER_ID"]').next().next().text("Yêu cầu nhập 'Giới tính' ");
                checkValue = false;
            }

            var dataItem = {
                'LAST_NAME': lastName.val(),
                'MIDDLE_NAME': middleName.val(),
                'FIRST_NAME': firstName.val(),
                'GENDER_ID': gender.val(),
                'RESIDENT_ID': residentId.val(),
                'HOUSEHOLD_ID': householdId.val(),
                'ETHNIC_ID': ethnicId.val(),
                'RELATION_ID': relationId.val(),
                'RESIDENT_GROUP_ID': '',
                'IsBack': isback
            };
            if (checkValue == false) {
                checkDataRessident = false;
                

            } else {
                if (ethnicId.val().length > 0) {
                    datasend.push(dataItem);
                }
            }

        });
        if (!checkDataRessident) {
          
            return;
        }
        if (datasend.length <= 0) {
            $('#message').text('Yêu cầu nhập thông tin công dân.');
            return;
        }

        $("#divLoading").show();
        $('#btnNext').attr('disabled', true);
        $('#btnBack').attr('disabled', true);
        $.ajax({
            url: '@Url.Action("ResidentList","ONLINE")',
            contentType: 'application/json; charset=utf-8',
            dataType: 'html',
            method: 'POST',
            headers: {
                'VerificationToken': '@GetAntiForgeryToken()'
            },
            data: JSON.stringify(datasend),
            success: function (data, textStatus, jqXHR) {
                $('#formLogin').html(data);
                $("#divLoading").hide();
                $('#btnNext').removeAttr('disabled');
                $('#btnBack').removeAttr('disabled');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('Có lỗi xảy ra trong quá trình tải dữ liệu: ' + errorThrown);
            },
            complete: function (jqXHR, textStatus) {
                $("#divLoading").hide();
                $('#btnNext').removeAttrs('disabled');
                $('#btnBack').removeAttrs('disabled');
            }
        });
    }



    $("#divLoading").show();
    $('#btnNext').attr('disabled', true);
    $('#btnBack').attr('disabled', true);

    $.ajax({
        url: '@Url.Action("GetAllByListName")',
        dataType: 'json',
        method: 'get',
        data: { 'tablename': 'ETHNIC' },
        success: function (data, textStatus, jqXHR) {
            var myOptions = '<option value="">-- Chọn dân tộc --</option>';
            $.each(data, function (i, item) {

                myOptions += '<option value="' + item.CodeID + '">' +
                     item.Name + '</option>';

            });
            $(".ETHNIC_ID_DROPDOWN").append(myOptions);
            $(".ETHNIC_ID_DROPDOWN").each(function (i, item) {
                $(item).val($(item).next().val());
            });
        },
        complete: function () {

            $.ajax({
                url: '@Url.Action("GetAllByListName")',
                dataType: 'json',
                method: 'get',
                data: { 'tablename': 'GENDER' },
                success: function (data, textStatus, jqXHR) {
                    var myOption = '<option value="">-- Chọn giới tính --</option>';
                   
                    $.each(data, function (i, item) {
                       
                        myOption += '<option value="' + item.CodeID + '">' +
                                                item.Name + '</option>';

                    });

                    $(".GENDER_ID_DROPDOWN").append(myOption);
                    $('.GENDER_ID_DROPDOWN').each(function (i, item) {
                        $(item).val($(item).next().val());
                    });

                },
                complete: function () {
                    $.ajax({
                        url: '@Url.Action("GetAllByListName")',
                        dataType: 'json',
                        method: 'get',
                        data: { 'tablename': 'RELATION' },
                        success: function (data, textStatus, jqXHR) {
                            var myOptions = '<option value="">-- Chọn quan hệ với chủ hộ --</option>';
                            $.each(data, function (i, item) {
                                myOptions += '<option value="' + item.CodeID + '">' +
                                     item.Name + '</option>';
                              

                            });
                            $(".RELATION_ID_DROPDOWN").append(myOptions);
                            $(".RELATION_ID_DROPDOWN").each(function (i, item) {
                                $(item).val($(item).next().val());
                            });
                        },
                        complete: function () {
                            $("#divLoading").hide();
                            $('#btnNext').removeAttrs('disabled');
                            $('#btnBack').removeAttrs('disabled');
                        }
                    });

                }

            });
        }
    });



</script>
<style>
    #dialog-confirm {
        height: 35px;
    }

    .ui-widget-header {
        border: 1px solid rgb(0,153,153);
        background: rgb(0,153,153) url("images/ui-bg_gloss-wave_35_f6a828_500x100.png") 50% 50% repeat-x;
    }

    .ui-dialog-titlebar-close {
        display: none;
    }

    .ui-dialog .ui-dialog-content {
        overflow: hidden;
        height: 1% !important;
    }

    .col-md-2 {
        padding-left: 2px;
    }

    .control {
        padding-right: 0px;
    }

    .control1 {
        padding: 0.5px;
    }

    .control2 {
        height: 30px;
    }
</style>

@if (Model.Count > 0)
{
    <div class="noidung" id="divLoadPartial">
        <div class="row">
            <div class="col-md-2 row-col-online">Quan hệ với chủ hộ</div>
            <div class="col-md-2 row-col-online widthnew">Họ<span class="text-danger">*</span></div>
            <div class="col-md-2 row-col-online">Tên đệm</div>
            <div class="col-md-2 row-col-online widthnew">Tên khai sinh<span class="text-danger">*</span></div>
            <div class="col-md-1 row-col-online gioitinh">Giới tính<span class="text-danger">*</span></div>
            <div class="col-md-1 row-col-online">Dân tộc<span class="text-danger">*</span></div>
        </div>
        <div id="divResidentList">
            @for (int i = 0; i < Model.Count; i++)
            {
                <div class="row row-col-online datarow">
                    <div class="col-md-2 control">
                        <select class="RELATION_ID_DROPDOWN form-control control2 " name="RELATION_ID"></select>
                        <input type="hidden" name="RELATION_ID_HIDDEN" value="@Model[i].RELATION_ID" />
                    </div>
                    <div class="col-md-2 control widthnew">
                        <input hidden="hidden" name="RESIDENT_ID" value="@Model[i].RESIDENT_ID" />
                        <input hidden="hidden" name="HOUSEHOLD_ID" value="@Model[i].HOUSEHOLD_ID" />
                        <input type="text" name="LAST_NAME" value="@Model[i].LAST_NAME" maxlength="50" class="form-control txt-online" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-2 control">
                        <input type="text" name="MIDDLE_NAME" value="@Model[i].MIDDLE_NAME" maxlength="150" class="form-control txt-online" />

                    </div>
                    <div class="col-md-2 control widthnew">
                        <input type="text" name="FIRST_NAME" value="@Model[i].FIRST_NAME" maxlength="50" class="form-control txt-online" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-1 control1 ">
                        <select class="GENDER_ID_DROPDOWN form-control control2  " name="GENDER_ID"></select>
                        <input type="hidden" name="GENDER_ID_HIDDEN" value="@Model[i].GENDER_ID" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-1 control1">

                        <select class="ETHNIC_ID_DROPDOWN form-control control2" name="ETHNIC_ID"></select>
                        <input type="hidden" name="ETHNIC_ID_HIDDEN" value="@Model[i].ETHNIC_ID" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="row row-col-online danger">
                    </div>
                </div>
            }
            <div id="divAddNewResident" hidden="hidden">
                <div class="row row-col-online datarow">
                    <div class="col-md-2 control">
                        <select class="RELATION_ID_DROPDOWN form-control control2" name="RELATION_ID"></select>
                        <input type="hidden" name="RELATION_ID_HIDDEN" value="" />
                    </div>
                    <div class="col-md-2 control widthnew">
                        <input hidden="hidden" name="RESIDENT_ID" value="" />
                        <input hidden="hidden" name="HOUSEHOLD_ID" value="@Model[0].HOUSEHOLD_ID" />
                        <input type="text" name="LAST_NAME" maxlength="50" class="form-control txt-online" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-2 control">
                        <input type="text" name="MIDDLE_NAME" maxlength="150" class="form-control txt-online" />
                    </div>
                    <div class="col-md-2 control widthnew">
                        <input type="text" name="FIRST_NAME" maxlength="50" class="form-control txt-online" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-1 control1 ">
                        <select class="GENDER_ID_DROPDOWN form-control control2" name="GENDER_ID"></select>
                        <input type="hidden" name="GENDER_ID_HIDDEN" value="" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>
                    <div class="col-md-1 control1">
                        <select class="ETHNIC_ID_DROPDOWN form-control control2" name="ETHNIC_ID"></select>
                        <input type="hidden" name="ETHNIC_ID_HIDDEN" value="" />
                        <span class="text-danger validation-summary-errors">
                        </span>
                    </div>

                </div>
            </div>
        </div>
        <div class="row row-col-online">
            <div class="col-md-offset-7">
                <button class="btn btn-link " id="btnAddResident" type="button">
                    Thêm mới
                </button>
            </div>
        </div>
        <div class="row-online">
            <center>
                <input type="button" id="btnBack" class="btn btn-small btn-small_online buttonClick  btn-success " value="<< Quay lại" />
                <input type="button" id="btnNext" class="btn btn-small btn-small_online btn-success buttonClick" value="Tiếp tục >>" />
            </center>
        </div>
        <div class="row-online">
            <span class="text-danger validation-summary-errors" id="message">
            </span>
        </div>
        <div id="dialog-confirm" title="Thông Báo !" style="display: none; ">
            <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Bạn có muốn thay đổi chủ hộ hay không ?</p>
        </div>
    </div>
}

